package org.lanqiao.ssm.facede.auth.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.lanqiao.ssm.common.constant.BaseConstant;
import org.lanqiao.ssm.common.constant.LoginConstant;
import org.lanqiao.ssm.common.core.dao.BaseDAO;
import org.lanqiao.ssm.common.core.service.BaseService;
import org.lanqiao.ssm.common.exceptions.BizException;
import org.lanqiao.ssm.common.exceptions.LoginException;
import org.lanqiao.ssm.facede.auth.dao.UserMapper;
import org.lanqiao.ssm.facede.auth.dao.UserRoleMapper;
import org.lanqiao.ssm.facede.auth.model.User;
import org.lanqiao.ssm.facede.auth.model.UserRole;
import org.lanqiao.ssm.facede.auth.service.UserServiceI;
import org.lanqiao.ssm.facede.auth.util.Encryption;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service("userService")
public class UserServiceImpl extends BaseService<User, String> implements UserServiceI {
	@Resource
	private UserMapper userMapper;
	@Resource
	private UserRoleMapper userRoleMapper;

	@Override
	public BaseDAO<User, String> getDao() {
		return userMapper;
	}

	@Override
	public User login(User u) {
		if (StringUtils.isEmpty(u.getLoginName()) || StringUtils.isEmpty(u.getLoginName())) {
			throw LoginException.LOGIN_PARAM_0;
		}
		return userMapper.login(u);
	}

	@Override
	public PageInfo<User> findUserAndRoles(User user, int page, int pageShow) {
		PageHelper.startPage(page, pageShow);
		List<User> list = userMapper.findUserAndRoles(user);
		return new PageInfo<User>(list);
	}

	@Override
	public int edit(User u) {
		int updateByPrimaryKey = userMapper.updateByPrimaryKeySelective(u);
		if (updateByPrimaryKey == 0) {
			throw BizException.DB_UPDATE_RESULT_0;

		} else {
			userRoleMapper.deleteUserRoleByUserId(u.getId());
			if (u.getRoleIds() != null) {
				for (String roleId : u.getRoleIds().split(",")) {
					UserRole ur = new UserRole();
					ur.setId(UUID.randomUUID().toString());
					ur.setUserId(u.getId());
					ur.setRoleId(roleId);
					int insert = userRoleMapper.insert(ur);
					if (insert == 0)
						throw BizException.DB_INSERT_RESULT_0;
				}
			}
		}
		return updateByPrimaryKey;
	}

	@Override
	public int insertSelective(User record) {
		if (StringUtils.isEmpty(record.getId()))
			record.setId(UUID.randomUUID().toString());
		record.setCreatetime(new Date());
		record.setStatus(LoginConstant.NORMAL_USER);
		record.setType(BaseConstant.NUMBER_ONE);
		record.setPassword(Encryption.Sha256Hash(record.getPassword()));
		return super.insertSelective(record);
	}

	@Override
	public User findUserByLoginName(String loginName) {
		if (StringUtils.isEmpty(loginName))
			throw LoginException.LOGIN_PARAM_0;
		return userMapper.findUserByLoginName(loginName);

	}

}
